package com.gm.wholesale.module.order.view;

import android.content.Context;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.util.ArrayMap;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.gm.commonlib.base.baseBean.BaseListResp;
import com.gm.commonlib.base.baseBean.BasePageData;
import com.gm.commonlib.base.baseBean.BaseResp;
import com.gm.commonlib.base.baseBean.DataResp;
import com.gm.commonlib.filters.RegexConstant;
import com.gm.commonlib.filters.RegexResultFilter;
import com.gm.commonlib.network.BaseHttpObserver;
import com.gm.commonlib.util.numberUtils.NumberUtils;
import com.gm.commonlib.util.stringUtils.StringUtils;
import com.gm.commonlib.util.viewUtils.RepeatClickUtils;
import com.gm.commonlib.views.popupwindow.Popupwindow;
import com.gm.commonlib.views.popupwindow.Popupwindow2;
import com.gm.commonlib.views.toast.ToastUtil;
import com.gm.wholesale.R;
import com.gm.wholesale.bluetooth.bean.WeightBean;
import com.gm.wholesale.cacheData.CacheData;
import com.gm.wholesale.constant.Unit;
import com.gm.wholesale.module.custom.ChoiceCustomData;
import com.gm.wholesale.module.custom.bean.CustomBean;
import com.gm.wholesale.module.good.GoodType;
import com.gm.wholesale.module.good.bean.GoodBean;
import com.gm.wholesale.module.good.bean.GoodListBean;
import com.gm.wholesale.module.good.model.GoodModel;
import com.gm.wholesale.module.main.ui.MainActivity;
import com.gm.wholesale.module.order.bean.AddWeightBean;
import com.gm.wholesale.module.order.bean.OrderRecmPriceBean;
import com.gm.wholesale.module.order.model.OrderModel;
import com.gm.wholesale.module.unit.bean.UnitBean;
import com.gm.wholesale.module.unit.model.UnitModel;
import com.gm.wholesale.util.CloneUtil;
import com.gm.wholesale.util.Utils;
import com.gm.wholesale.view.MyTextWatcher;
import com.gm.wholesale.view.NumberInputView;

import java.util.ArrayList;
import java.util.List;

public class CreateOrderView extends LinearLayout {
    private static final String defaultPrice = "小计: 0.00元";
    private TextView totalTv;

    public TextView mChoiceUnitTv;

    public AddWeightView addWeightView;
    private LinearLayout numberInputLinView;
    private LinearLayout priceInputLinView;

    private View mLeftView;
    public String mTempGoodId;

    public CreateOrderView(Context context) {
        super(context);
        initView(context);
    }

    public CreateOrderView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    private View closeView;
    public EditText numberInputEd;
    public TextView goodUnitTv;
    public TextView moneyUnitTv;
    public TextView goodNameTv;
    public EditText priceInputEd;
    public NumberInputView numberInputView;
    public GoodBean mGoodBean;
    private ICreateOrderListener listener;
    public OrderRightFunctionView orderRightFunctionView;

    private WeightBean mWeightBean;
    public MainActivity mainActivity;


    public interface ICreateOrderListener {
        void onCreateOrder(GoodBean goodBean);
    }

    public void setICreateOrderListener(ICreateOrderListener listener) {
        this.listener = listener;
    }

    public void initView(Context context) {
        LayoutInflater.from(context).inflate(R.layout.fragment_menu_right, this);
        mLeftView=findViewById(R.id.leftView);
        totalTv = findViewById(R.id.totalTv);
        mChoiceUnitTv = findViewById(R.id.choiceUnitTv);
        closeView = findViewById(R.id.closeView);
        numberInputEd = findViewById(R.id.numberInputEd);
        goodUnitTv = findViewById(R.id.goodUnitTv);
        priceInputEd = findViewById(R.id.priceInputEd);
        numberInputView = findViewById(R.id.numberInputView);
        goodNameTv = findViewById(R.id.goodNameTv);
        addWeightView = findViewById(R.id.addWeightView);
        numberInputLinView = findViewById(R.id.numberInputLinView);
        priceInputLinView = findViewById(R.id.priceInputLinView);
        orderRightFunctionView = findViewById(R.id.rightFunctionView);
        moneyUnitTv = findViewById(R.id.moneyUnit);
        orderRightFunctionView.setCreateOrderView(this);
        numberInputLinView.setBackgroundResource(R.drawable.ed_get_fos_);
        numberInputEd.setFilters(new InputFilter[]{new RegexResultFilter(RegexConstant.MAX_MONEY_VALUE_92)});
        priceInputEd.setFilters(new InputFilter[]{new RegexResultFilter(RegexConstant.MAX_MONEY_VALUE_92)});
        numberInputEd.addTextChangedListener(new MyTextWatcher() {
            @Override
            public void afterTextChanged(Editable editable) {
                computeTotalPrice(editable.toString(),
                        priceInputEd.getText().toString());
            }
        });
        priceInputEd.addTextChangedListener(new MyTextWatcher() {
            @Override
            public void afterTextChanged(Editable editable) {
                computeTotalPrice(numberInputEd.getText().toString(),
                        editable.toString());
            }
        });

        numberInputView.setINumberView(() -> {
            if (RepeatClickUtils.check()) {
                return;
            }
            if (numberInputView.getBindEd().getId()==R.id.numberInputEd){
                numberInputView.bindEdiText(priceInputEd,"");
                priceInputEd.requestFocus();
                numberInputEd.clearFocus();
                return;
            }
            String numbers = numberInputEd.getText().toString();
            String prices = priceInputEd.getText().toString();
            double addTotalWeight = addWeightView.getTotalWeight();

            double inputNum = 0;
            if (!TextUtils.isEmpty(numbers)) {
                inputNum = Double.parseDouble(numbers);
            }
            //todo 看是语音创建还是非语言创建
            mGoodBean.setIsVoiceCreate(isCreateByVoice());
            // 显示则是 选择单位，单位从选择控件获取
            if (mChoiceUnitTv.getVisibility() == VISIBLE) {
                mGoodBean.setUnitName(mChoiceUnitTv.getText().toString());
            }
            // todo 先从累加称重里面获取，有直接使用。没有的话从当前输入框获取
            if (addTotalWeight > 0) {
                mGoodBean.setGoodNum(addTotalWeight);
                mGoodBean.setAddWeightBeans(addWeightView.getAddWeight());
            } else {
                mGoodBean.setGoodNum(inputNum);
            }
             // todo 当前输入框没有数据 并且 累加称重没有数据，提示输入
            if (inputNum <= 0
                    && addTotalWeight <= 0) {
                ToastUtil.showToast("数量不能小于或等于0");
                return;
            }
            if (!TextUtils.isEmpty(prices)) {
                mGoodBean.setPrice(Double.parseDouble(prices));
            } else {
                mGoodBean.setPrice(0);
            }
            if (listener != null) {
                listener.onCreateOrder(mGoodBean);
            }
            Popupwindow.hiddenPop();
        });
        numberInputEd.setOnFocusChangeListener((view, b) -> {
            if (b) {
                numberInputLinView.setBackgroundResource(R.drawable.ed_get_fos_);
                priceInputLinView.setBackgroundResource(R.drawable.white_y_shap);
                String text = numberInputEd.getText().toString();
                numberInputView.bindEdiText(numberInputEd, text);
            }


        });

        priceInputEd.setOnFocusChangeListener((view, b) -> {
            if (b) {
                priceInputLinView.setBackgroundResource(R.drawable.ed_get_fos_);
                numberInputLinView.setBackgroundResource(R.drawable.white_y_shap);
                String text = priceInputEd.getText().toString();
                numberInputView.bindEdiText(priceInputEd, text);
            }

        });
        goodUnitTv.setOnClickListener(view -> numberInputEd.requestFocus());
        moneyUnitTv.setOnClickListener(view -> priceInputEd.requestFocus());

        closeView.setOnClickListener(view -> Popupwindow.hiddenPop());
        mLeftView.setOnClickListener(v -> Popupwindow.hiddenPop());


    }

    public boolean isCreateByVoice() {
        return false;
    }

    public synchronized void setBlueNumber(WeightBean weightBean) {

        if (weightBean == null) return;
        if (mWeightBean == null) {
            mWeightBean = CloneUtil.clone(weightBean);
        } else {
            if (weightBean.getWeightNum() == mWeightBean.getWeightNum()) {
                return;
            } else {
                mWeightBean = CloneUtil.clone(weightBean);
            }
        }
        if ( Utils.isWeightUnit(mGoodBean.getUnitName())) {
            double newWeight = Unit.getWeight(weightBean.getsUnit(), mGoodBean.getUnitName(),
                    weightBean.getWeightNum());
            if (newWeight>0){
                numberInputEd.setText(NumberUtils.getMoneyString(newWeight));
                String datas = numberInputEd.getText().toString();
                numberInputEd.setSelection(datas.length());

                String price = priceInputEd.getText().toString();
                //价格没得，跳转到价格获取焦点,不然不管
                if (StringUtils.isEmpty(price) || Double.parseDouble(price)==0) {
                    priceInputEd.requestFocus();
                    numberInputEd.clearFocus();
                }
            }
            else {
                numberInputEd.setText("");
                numberInputEd.requestFocus();
                priceInputEd.clearFocus();
            }

        }


    }

    private void computeTotalPrice(String nums, String prices) {
        try {
            double num = 0;
            double price = 0;
            if (!TextUtils.isEmpty(nums)
                    && !TextUtils.isEmpty(prices)) {
                num = Double.parseDouble(nums);
                price = Double.parseDouble(prices);
                double total = NumberUtils.mul(num, price);
                totalTv.setText("小计: " + NumberUtils.getMoneyString(total) + "元");
            } else {
                totalTv.setText(defaultPrice);
            }
        }
        catch (Exception e){

        }

    }

    // todo 设置价格
    public void setPrice(String price) {
        if (!TextUtils.isEmpty(price)) {
            String priceS=NumberUtils.subZeroAndDot(price);
            priceInputEd.setText(priceS);
            priceInputEd.setSelection(priceS.length());
        }
        else {
            priceInputEd.setText("");
        }
    }

    //todo 接口获取价格后，填入价格，但是还得判断设置是否开启自动填入价格
    public void autoSetPrice(double price) {
        //todo 修改时候，不自动填入价格，不然把原来数据覆盖了
        if (mGoodBean == null || mGoodBean.isIsUpdateView()) {
            return;
        }
        //todo 需要判断设置里面是否开启自动填入价格。设置关闭，则不填入
        boolean isAutoInputPrice = CacheData.getIsAutoInputPrice();
        if (price > 0 && isAutoInputPrice) {
            setPrice(NumberUtils.getMoneyString(price));
        }
        handelInputEdFocus();


    }

    public void reset() {
        mTempGoodId = "";
        mWeightBean = null;
        numberInputEd.setText("");
        // todo 累加称重重置
        addWeightView.reset();
        priceInputEd.setText("");
        totalTv.setText(defaultPrice);
        mChoiceUnitTv.setVisibility(GONE);
        mChoiceUnitTv.setText("斤");
        goodUnitTv.setVisibility(VISIBLE);
        orderRightFunctionView.reset();

    }

    //todo 根据名字完全匹配商品
    //点击商品创建订单》》
    public void getGoodByName(String text,String unitName) {
        ArrayMap<String, Object> queryData = new ArrayMap<>();
        queryData.put("name", text);
        if (!TextUtils.isEmpty(unitName)){
            queryData.put("unitName", text);
        }
        GoodModel.getSearchGood(null, queryData, new BaseHttpObserver<>() {
            @Override
            protected void handleResultOkResp(BaseListResp<GoodBean> resp) {
                updateView(resp.getDatas());
            }

            @Override
            protected void handleResultOtherResp(BaseListResp<GoodBean> resp) {
                updateView(null);
            }

            @Override
            protected void handleErrorBaseResp(BaseResp baseResp) {
                updateView(null);
            }
        });
    }

    public void getGoodByNameAndUnit(String text,String unitName) {
        ArrayMap<String, Object> queryData = new ArrayMap<>();
        queryData.put("name", text);
        if (!TextUtils.isEmpty(unitName)){
            queryData.put("unitName", unitName);
        }
        GoodModel.getSearchGood(null, queryData, new BaseHttpObserver<>() {
            @Override
            protected void handleResultOkResp(BaseListResp<GoodBean> resp) {
                if (resp.getDatas()!=null && !resp.getDatas().isEmpty()){
                    updateView(resp.getDatas());
                }


            }


        });
    }

    // todo 点击商品录单和语音录单 不一样，语音录单重写该方法.
    //  列表点击商品录单，不用调用接口查询数据，不会走这里，语音录单才会走这里，重新该方法
    public void updateView(List<GoodBean> goodBeans) {

    }

    // todo 点击商品专用
    public void showChoiceGoodView(MainActivity activity, GoodBean goodBean) {
        showBaseView(activity, goodBean);
    }


    public void showBaseView(MainActivity activity, GoodBean goodBean) {
        mainActivity = activity;
        if (goodBean == null) {
            return;
        }
        reset();
        mGoodBean = goodBean;
        handleRightWeightView(); //称重和累加称重，非重量单位不显示
        handleShowGoodPriceView();//是否显示商品价格
        getOrderRecPrice();//获取商品价格
        //todo 修改訂單，回显数据 （不是修改的话，数量从秤获取，单价从接口获取（单价在设置里面设置了显示才显示））
        if (mGoodBean.isIsUpdateView()) {
            if (goodBean.getGoodNum() >= 0) {
                numberInputEd.setText(NumberUtils.subZeroAndDot(goodBean.getGoodNum() + ""));
            }
            if (goodBean.getPrice() >= 0) {
                priceInputEd.setText(NumberUtils.subZeroAndDot(goodBean.getPrice() + ""));
            }
            if (goodBean.getAddWeightBeans()!=null){
                addWeightView.showView(goodBean.getAddWeightBeans());
            }
        }
        goodNameTv.setText(mGoodBean.getName());
        if (!TextUtils.isEmpty(mGoodBean.getUnitName())) {
            goodUnitTv.setText(mGoodBean.getUnitName());
        }
        //todo 临时商品 和非库存商品，单位可以切换选择
        if (mGoodBean.isTemporaryGood() || goodBean.getType()== GoodType.UN_INVENTORY_GOOD) {
            mChoiceUnitTv.setVisibility(VISIBLE);
            mChoiceUnitTv.setText(mGoodBean.getUnitName());
            goodUnitTv.setVisibility(GONE);
            //todo 设置单位可以选择
            showUnitViewByApi();
        }
        else { //库存商品，切换单位
            List<GoodListBean.UnitsBean> unitsBeans=goodBean.getUnits();
            //单位大于1个可以切换单位
            if (unitsBeans!=null && unitsBeans.size()>1){
                mChoiceUnitTv.setVisibility(VISIBLE);
                mChoiceUnitTv.setText(mGoodBean.getUnitName());
                goodUnitTv.setVisibility(GONE);
                mChoiceUnitTv.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        List<UnitBean> unitBeans=goodBean.getUnitData();
                        showUnitChoiceByInventoryView(unitBeans,mChoiceUnitTv);

                    }
                });
            }
            else {
                mChoiceUnitTv.setVisibility(GONE);
                goodUnitTv.setText(mGoodBean.getUnitName());
                goodUnitTv.setVisibility(VISIBLE);
            }
        }
        //todo 设置 数量和单价 哪个输入框获取焦点
        handelInputEdFocus();


    }

    //todo 临时商品和非库存商品 获取全部的单位 以便用来切换
    public void showUnitViewByApi() {
        //有单位 回显单位
        if (!TextUtils.isEmpty(mGoodBean.getUnitName())) {
            mChoiceUnitTv.setText(mGoodBean.getUnitName());
        }
        mChoiceUnitTv.setVisibility(VISIBLE);
        goodUnitTv.setVisibility(GONE);
        mChoiceUnitTv.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                UnitModel.getUnits(mainActivity, new BaseHttpObserver<>() {
                    @Override
                    protected void handleResultOkResp(BasePageData<UnitBean> resp) {
                        super.handleResultOkResp(resp);
                        if (resp != null) {
                            showView(resp.getData().getDatas(), view);
                        }
                    }
                });

            }
        });
    }

    public void showUnitByData(List<GoodBean> goods) {
        mChoiceUnitTv.setVisibility(VISIBLE);
        goodUnitTv.setVisibility(GONE);
        if (goods == null || goods.isEmpty()) {
            return;
        }
        List<UnitBean> unitBeans = new ArrayList<>();
        for (GoodBean goodBean : goods) {
            UnitBean unitBean = new UnitBean();
            unitBean.setId(goodBean.getUnitId());
            unitBean.setName(goodBean.getUnitName());
            unitBean.setPrice(goodBean.getPrice()+"");
            unitBean.setGoodId(goodBean.getId());
            unitBean.setGoodName(goodBean.getName());
            unitBeans.add(unitBean);
        }
        mChoiceUnitTv.setOnClickListener(view -> showView(unitBeans, view));

    }

    //todo 库存商品选择单位
    private void showUnitChoiceByInventoryView(List<UnitBean> unitBeans, View view) {
        if (unitBeans==null)return;
        ChoiceUnitView choiceUnitView = new ChoiceUnitView(mainActivity);
        choiceUnitView.showView(unitBeans);
        choiceUnitView.setOnChoiceUnitListener(unitBean -> {

            mGoodBean.setUnitName(unitBean.getName());
            mGoodBean.setUnitId(unitBean.getId());
            setPrice(unitBean.getPrice());
            if (Utils.isWeightUnit(unitBean.getName())) {
                orderRightFunctionView.showWeightView();
            } else {
                orderRightFunctionView.hidWeightView();
            }
            if (addWeightView != null) {
                addWeightView.updateByChangeUnit(unitBean.getName());
            }
            mChoiceUnitTv.setText(unitBean.getName());

        });
        Popupwindow2.showPopView(mainActivity, view, choiceUnitView);
    }



    private void showView(List<UnitBean> unitBeans, View view) {
        ChoiceUnitView choiceUnitView = new ChoiceUnitView(mainActivity);
        choiceUnitView.showView(unitBeans);
        choiceUnitView.setOnChoiceUnitListener(unitBean -> {

            mGoodBean.setUnitName(unitBean.getName());
            mGoodBean.setUnitId(unitBean.getId());
            if (unitBean.getGoodId()>0){
                mGoodBean.setId(unitBean.getGoodId());
            }
            if (!TextUtils.isEmpty(unitBean.getGoodName())){
                mGoodBean.setName(unitBean.getGoodName());
            }
            if (mGoodBean.getId()>0){
                getOrderRecPrice();
            }
            if (Utils.isWeightUnit(unitBean.getName())) {
                orderRightFunctionView.showWeightView();
            } else {
                orderRightFunctionView.hidWeightView();
            }
            if (addWeightView != null) {
                addWeightView.updateByChangeUnit(unitBean.getName());
            }
            if (!TextUtils.isEmpty(unitBean.getGoodName())) {
                goodNameTv.setText(unitBean.getGoodName());
            }
            mChoiceUnitTv.setText(unitBean.getName());
            //主要用于查询商品是不是新商品，已存在，赋值商品id（id》0 则不是新商品了，用于主界面列表显示要不要加新图标）
            if (mGoodBean.getId()<=0){
                getGoodByNameAndUnit(mGoodBean.getName(),unitBean.getName());
            }

        });
        Popupwindow2.showPopView(mainActivity, view, choiceUnitView);
    }


    public void handelInputEdFocus() {
        //todo 默认焦点到没得数据的输入框，都有数据则 焦点位于数量输入框
        String number = numberInputEd.getText().toString();
        String price = priceInputEd.getText().toString();
        if (StringUtils.isEmpty(number) || Double.parseDouble(number)<=0) {
            numberInputEd.requestFocus();
            priceInputEd.clearFocus();
            return;
        }
        if (StringUtils.isEmpty(price) || Double.parseDouble(price)<=0) {
            priceInputEd.requestFocus();
            numberInputEd.clearFocus();
            return;
        }
        numberInputEd.requestFocus();
        priceInputEd.clearFocus();


    }

    public void handleShowGoodPriceView() {
        // todo 新商品直接隐藏
        if (mGoodBean != null && mGoodBean.getId() <= 0) {
            orderRightFunctionView.hidPrice();
        } else { //todo 设置里面 打开开关
            if (CacheData.getShowPriceView()) {
                orderRightFunctionView.showPrice();
                return;
            }
            orderRightFunctionView.hidPrice();
        }

    }

    //todo 重量单位才显示称重和累加称重
    public void handleRightWeightView() {
        if (mGoodBean == null) return;
        if (mGoodBean.isWeightUnit()) {
            orderRightFunctionView.showWeightView();
        } else {
            orderRightFunctionView.hidWeightView();
        }
    }


    public void getOrderRecPrice() {
        if (mGoodBean == null || mGoodBean.getId() <= 0) return;
        CustomBean customBean = ChoiceCustomData.newInstance().getCustomBean();
        ArrayMap<String, Object> queryData = new ArrayMap<>();
        if (customBean != null) {
            queryData.put("customerID", customBean.getId());
            queryData.put("skuID", mGoodBean.getId());
            OrderModel.getOrderRecPrice(null, queryData, new BaseHttpObserver<>() {
                @Override
                protected void handleResultOkResp(DataResp<OrderRecmPriceBean> resp) {
                    if (resp != null) {
                        orderRightFunctionView.updateView(resp.getData());
                    }
                }

                @Override
                protected void handleResultOtherResp(DataResp<OrderRecmPriceBean> resp) {

                }
            });
        }

    }

    public void getWeightByMachine() {
        //todo 点击称重时候连接蓝牙秤（没有连接会再次连接，主界面进来会连接一次）
        mainActivity.startConnection();
        if (mWeightBean != null && mGoodBean != null) {
            double weight = Unit.getWeight(mWeightBean.getsUnit(), mGoodBean.getUnitName(), mWeightBean.getWeightNum());
            if (weight > 0) {
                numberInputEd.setText(NumberUtils.getMoneyString(weight));
                String datas = numberInputEd.getText().toString();
                numberInputEd.setSelection(datas.length());
            }

        }

    }

    public void hidRightPrice() {
        orderRightFunctionView.hidPrice();
    }


    public void shoAddWeightView() {
        String goodNum = numberInputEd.getText().toString();
        if (TextUtils.isEmpty(goodNum)) {
            ToastUtil.showToast("请输入数量");
            return;
        }
        if (Double.parseDouble(goodNum) <= 0) {
            ToastUtil.showToast("数量不能为0");
            return;
        }
        addWeightView.setVisibility(VISIBLE);
        AddWeightBean addWeightBean = new AddWeightBean();
        addWeightBean.setWeight(Double.parseDouble(goodNum));
        addWeightBean.setUnit(mGoodBean.getUnitName());
        addWeightView.showView(addWeightBean);
        numberInputEd.setText("");
    }
}
